<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>

  </style>
</head>
<body>
  <div>
    <button id="startId">开始动画</button>
    <div id="requestAnimationFrameSelector">

    </div>
  </div>
</body>
<script>
  document.getElementById('startId').onclick = function() {
    start();
  }
  // 开始动画按钮的点击事件
function start() {
  window.startTime = Date.now()
  animationByRaf()
  // animationBySetInterval()
}
// requestAnimationFrame动画
function animationByRaf(val = 1, now = Date.now(), times = 0, maxPeriod = 0){
  requestAnimationFrame(() => {
    const jiangeTime = Date.now() - now;
    console.log('间隔时间：', jiangeTime)
    if(jiangeTime > 20) {
      // 帧间隔时长大于20ms，认为卡顿
      // 收集卡顿次数
      times++
      // 收集最大卡顿间隔
      maxPeriod = Math.max(maxPeriod, jiangeTime)
    }
    // 更新动画的开始时间，与下一帧动画的Date.now()相减计算出帧间隔时长
    now = Date.now()

    // 水平移动动画，每帧移动1px
    document.querySelector(`#requestAnimationFrameSelector`).style.left = `${val}px`;

    if(val >= 500) {
      // 移动500px后动画停止，打印日志
      console.log(`requestAnimationFrame动画耗时${Math.floor(Date.now() - startTime)}，卡顿次数${times}，最长卡顿${maxPeriod}ms`)
      return
    }
    // 递归调用实现动画
    animationByRaf(val+1, now, times, maxPeriod)
  })
}
</script>
</html>